package com.guoxin.jiyin.service.impl;

import com.guoxin.jiyin.exception.BlockChainException;

import com.guoxin.jiyin.service.BlockChainsService;
import com.guoxin.jiyin.service.ProjectService;
import com.guoxin.jiyin.utils.SysUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
public class ProjectServiceImpl implements ProjectService {

    private static final Logger logger = LogManager.getLogger(ProjectServiceImpl.class);

    @Autowired
    private BlockChainsService blockChainsService;


    @Override
    public void createUser(String token, String data) throws Exception {
        String value = blockChainsService.read(token);
        if (StringUtils.isEmpty(value)) {
            if (!blockChainsService.write(token, SysUtils.aesEncrypt(data))) {
                throw new BlockChainException();
            }
        } else {
            throw new BlockChainException();
        }
    }

    @Override
    public String getUser(String token) throws Exception {
        return SysUtils.aesDecrypt(blockChainsService.read(token));
    }

    @Override
    public void createReport(String token, String data) throws Exception {
//        String value = blockChainsService.read(token);
//        logger.info("read finished");
//        if (StringUtils.isEmpty(value)) {
            logger.info("start write");
            if (!blockChainsService.write(token, SysUtils.aesEncrypt(data))) {
                throw new BlockChainException();
            }
//        } else {
//            throw new BlockChainException();
//        }

    }

    @Override
    public String getReport(String token) throws Exception {
        return SysUtils.aesDecrypt(blockChainsService.read(token));
    }
}
